<template>
  <div class="chat-container">
    <!-- 左侧会话列表 -->
    <div class="sidebar">
      <!-- 头部 -->
      <div class="sidebar-header">
        <h2>即时通信</h2>
        <button class="refresh-btn" @click="handleRefresh">
          <i class="icon-refresh"></i>
        </button>
      </div>

      <!-- 搜索框 -->
      <div class="search-box">
        <input 
          v-model="searchKeyword"
          type="text" 
          placeholder="搜索会话..."
          class="search-input"
        >
      </div>

      <!-- 会话列表 -->
      <div class="conversation-list">
        <div
          v-for="conversation in filteredConversations"
          :key="conversation.conversationID"
          :class="['conversation-item', { active: imStore.currentConversation?.conversationID === conversation.conversationID }]"
          @click="selectConversation(conversation)"
        >
          <div class="avatar-container">
            <el-avatar :size="40" :src="getConversationAvatar(conversation)" :alt="getConversationName(conversation)">
              {{ getConversationName(conversation).charAt(0) }}
            </el-avatar>
            <span v-if="conversation.unreadCount > 0" class="unread-count">{{ conversation.unreadCount }}</span>
          </div>
          <div class="conversation-info">
            <div class="conversation-header">
              <span class="name">{{ getConversationName(conversation) }}</span>
              <span class="time">{{ formatTime(conversation.lastMessage?.lastTime) }}</span>
            </div>
            <p class="last-message">{{ getLastMessageText(conversation.lastMessage) }}</p>
          </div>
        </div>
        <div v-if="filteredConversations.length === 0" class="empty-state">
          <p>暂无会话</p>
        </div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">
      <!-- 空状态 -->
      <div v-if="!imStore.currentConversation" class="empty-state">
        <div class="empty-content">
          <div class="empty-icon">
            <i class="icon-message"></i>
          </div>
          <h3 class="empty-title">选择一个会话开始聊天</h3>
          <p class="empty-description">
            从左侧会话列表中选择好友，或者从联系人列表中发起新的对话
          </p>
          <div class="empty-actions">
            <button class="action-btn primary" @click="handleRefresh">
              <i class="icon-refresh"></i>
              刷新会话
            </button>
          </div>
        </div>
      </div>

      <!-- 有会话时显示聊天界面 -->
      <template v-else>
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="chat-user">
            <el-avatar :size="40" :src="getConversationAvatar(imStore.currentConversation)" :alt="getConversationName(imStore.currentConversation)">
              {{ getConversationName(imStore.currentConversation).charAt(0) }}
            </el-avatar>
            <div class="user-info">
              <h3>{{ getConversationName(imStore.currentConversation) }}</h3>
              <span class="user-status">
                未知
              </span>
            </div>
          </div>
          <div class="user-profile">
            <!-- 在消息区域顶部添加操作按钮 -->
            <!-- <el-button 
              type="danger" 
              size="small" 
              :icon="Delete"
              @click="confirmDeleteAllMessages"
              :disabled="imStore.messageList.length === 0"
            >
              删除全部消息
            </el-button> -->
            <!-- 获取用户信息 -->
            <!-- <el-button type="text" @click="showUserInfo(imStore.currentConversation.userProfile)">
              <i class="i-lucide:user h-5 w-5"></i>
            </el-button> -->
          </div>
        </div>

        <!-- 消息区域 -->
        <div class="message-area" ref="messageContainer" @wheel="handleWheel">

          <div
            v-if="imStore.messageList.length === 0"
            class="py-8 text-center text-gray-500"
          >
            <p>暂无消息，开始聊天吧！</p>
          </div>

          <!-- 在消息列表顶部添加 -->
          <div v-if="isLoadingMore" class="loading-indicator">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>

          <div
            v-for="message in imStore.messageList"
            :key="message.ID"
            :data-message-id="message.ID"
            :class="['message-wrapper', { 'message-right': message.flow === 'out' }]"
          >
            <div class="message-avatar">
              <h1 v-if="anchorMessageId == message.ID">分界线</h1>
              <el-avatar :size="36" :src="message.avatar" :alt="message.nick">
                <!-- 如果是对方发来的显示对方的 -->
                <!-- 如果是自己发的显示我 -->
                {{ message.flow === 'out' ? '我' : message.nick?.charAt(0) || message.from?.charAt(0) }}
              </el-avatar>
            </div>
            <div class="message-content">
              <div class="message-info">
                <!-- 如果是对方发来的显示对方的 -->
                <!-- 如果是自己发的不显示 -->
                <span class="sender" v-if="message.flow === 'in'">{{ message.nick }}</span>
                <span class="time">{{ formatMessageTime(message.time) }}</span>
              </div>
              <div :class="['message-bubble', { 'bubble-self': message.flow === 'out' }]">
                <!-- 文本消息 -->
                <p v-if="message.type === 'TIMTextElem'" class="whitespace-pre-wrap">
                  {{ message.payload?.text }}
                </p>

                <!-- 自定义消息 -->
                <div v-else-if="message.type === 'TIMCustomElem'" class="custom-message">
                  <!-- 采购公告 -->
                  <div v-if="parseCustomMessage(message)?.type === 'procurement_notice'" class="procurement-notice">
                    <div class="notice-header">
                      <img class="mr2" src="/@/assets/gouwuche.png" style="width: 26px; height: 26px;" alt="">
                      <span class="font-semibold">{{ parseCustomMessage(message)?.title }}</span>
                    </div>
                    <p class="notice-content">
                      {{ parseCustomMessage(message)?.content }}
                    </p>
                    <div class="notice-details">
                      <div><strong>产品名称:</strong> {{ parseCustomMessage(message)?.productName }}</div>
                      <div><strong>产品编号:</strong> {{ parseCustomMessage(message)?.productCode }}</div>
                      <div><strong>数量:</strong> {{ parseCustomMessage(message)?.amount }}</div>
                      <div><strong>交期:</strong> {{ parseCustomMessage(message)?.deadline }}</div>
                      <div>
                        <strong>状态:</strong>
                        <span class="notice-status">
                          {{ parseCustomMessage(message)?.status === 'pending' ? '待处理'
                            : parseCustomMessage(message)?.status === 'approved' ? '已批准' : '已拒绝' }}
                        </span>
                      </div>
                      <div>
                        <strong>图片:</strong>
                        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
                          <img @click="handlerPreview(img)" style="width: 100%; height: 100%;object-fit: cover;cursor: pointer;" v-for="img in parseCustomMessage(message)?.productImg.split(',')" :key="img" :src="img" alt="">
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- 图片自定义消息 -->
                  <div v-else-if="parseCustomMessage(message)?.type === 'image'" class="custom-image-message">
                    <img 
                      :src="parseCustomMessage(message)?.imageUrl || parseCustomMessage(message)?.url" 
                      :alt="parseCustomMessage(message)?.description || '图片'"
                      class="custom-message-image"
                      @click="handlerPreview(parseCustomMessage(message)?.imageUrl || parseCustomMessage(message)?.url)"
                    />
                  </div>
                  <!-- 文件自定义消息 -->
                  <div v-else-if="parseCustomMessage(message)?.type === 'file'" class="custom-file-message">
                    <div class="file-container">
                      <span class="file-icon">{{ getFileIcon(parseCustomMessage(message)?.fileName) }}</span>
                      <div class="file-info">
                        <div class="file-name">{{ parseCustomMessage(message)?.fileName || '未知文件' }}</div>
                        <div class="file-size">{{ formatFileSize(parseCustomMessage(message)?.fileSize) }}</div>
                      </div>
                      <el-button type="text" class="file-download" v-if="parseCustomMessage(message)?.fileUrl" @click="downloadFile(parseCustomMessage(message)?.fileUrl, parseCustomMessage(message)?.fileName)">
                        <el-icon><Download /></el-icon>
                      </el-button>
                    </div>
                  </div>
                  <!-- 公告消息 -->
                  <div v-else-if="parseCustomMessage(message)?.type === 'announcement'" class="announcement-message">
                    <div class="announcement-header">
                      <span class="announcement-icon">📢</span>
                      <span class="announcement-title">{{ parseCustomMessage(message)?.title || '系统公告' }}</span>
                    </div>
                    <div class="announcement-content">
                      {{ parseCustomMessage(message)?.content }}
                    </div>
                    <div v-if="parseCustomMessage(message)?.date" class="announcement-date">
                      发布时间: {{ parseCustomMessage(message)?.date }}
                    </div>
                  </div>

                  <div v-else class="generic-custom">
                    <p>{{ parseCustomMessage(message)?.description || '[自定义消息]' }}</p>
                  </div>
                </div>

                <!-- 其他消息类型 -->
                <div v-else class="other-message">
                  <p>[{{ message.type }}]</p>
                </div>
              </div>
            </div>
          </div>
          <div v-if="imStore.messageList.length === 0" class="empty-state">
            <p>暂无消息</p>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-section">
          <div class="input-toolbar">
            <EmojiPicker @selectEmoji="handleEmojiSelect" />
            <button class="tool-btn" title="发送文件" @click="openImageUpload">📷</button>
            <!-- 图片上传弹窗 -->
            <ImageUploadDialog ref="imageUploadDialogRef" /> 
            <button class="tool-btn" title="发送文件"  @click="openFileUpload">📄</button>
            <FileUploadDialog ref="fileUploadDialogRef" />
          </div>
          <div class="input-row">
            <el-input
              ref="messageInputRef"
              v-model="inputMessage"
              type="textarea"
              :rows="3"
              placeholder="输入消息..."
              class="message-input"
              @keyup.enter.ctrl="sendMessage"
              @keyup.enter.meta="sendMessage"
            />
            <el-button type="primary" @click="sendMessage" class="send-btn">
              发送
            </el-button>
          </div>
          <div class="input-hint">按 Ctrl+Enter 发送</div>
        </div>
      </template>
    </div>

    <!-- 图片预览 -->
    <el-dialog v-model="dialogImageVisible" title="图片预览" width="30%">
      <img :src="previewImage" alt="预览" style="width: 100%;">
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch, nextTick } from 'vue'
import type { Conversation, Message } from 'tim-js-sdk'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { useIMStore } from '/@/stores/im'
import { Download, Loading, Delete } from '@element-plus/icons-vue'
import EmojiPicker from '/@/components/EmojiPicker.vue'
import ImageUploadDialog from '/@/components/ImageUploadDialog.vue'
import FileUploadDialog from '/@/components/fileUploadDialog.vue'



const imStore = useIMStore()
const dialogImageVisible = ref(false)
const previewImage = ref('')
const messageContainer = ref(null)
const imageUploadDialogRef = ref();

// 响应式数据
const searchKeyword = ref('')
const inputMessage = ref('')
// 表情包相关
const messageInputRef = ref(null)

// 添加状态变量
const isLoadingMore = ref(false)
const hasMoreMessages = ref(true)
const anchorMessageId = ref('') // 记录锚点消息ID
const shouldScrollToAnchor = ref(false) // 是否需要滚动到锚点
const fileUploadDialogRef = ref();

// 计算属性
const filteredConversations = computed(() => {
  if (!searchKeyword.value) {
    return imStore.conversationList
  }
  return imStore.conversationList.filter((conversation:any) => {
    const name = getConversationName(conversation)
    return name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  })
})


// 确认删除全部消息
const confirmDeleteAllMessages = async () => {
  if (!imStore.currentConversation) {
    ElMessage.warning('请先选择一个会话')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除与 ${getConversationName(imStore.currentConversation)} 的全部聊天记录吗？\n删除后无法恢复！`,
      '删除全部消息',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false,
      }
    )
    
    await deleteAllMessages()
  } catch (error) {
    // 用户取消删除
    console.log('取消删除全部消息')
  }
}

// 删除全部消息
const deleteAllMessages = async () => {
  if (!imStore.currentConversation) return
  
  try {
    await imStore.deleteAllMessages(imStore.currentConversation.conversationID)
    ElMessage.success('全部消息删除成功')
  } catch (error) {
    console.error('删除全部消息失败:', error)
    ElMessage.error('删除全部消息失败')
  }
}

// 滚动到指定消息位置
const scrollToMessage = (messageId: string, position: 'top' | 'center' | 'bottom' = 'center') => {
  if (!messageId) return
  
  const messageElement = messageContainer.value?.querySelector(`[data-message-id="${messageId}"]`)
  if (messageElement) {
    messageElement.scrollIntoView({ 
      block: position, 
      behavior: 'auto' // 瞬间滚动，无动画
    })
    console.log(`滚动到消息: ${messageId}`)
  }
}
// 处理鼠标滚轮事件
const handleWheel = (event: WheelEvent) => {
  console.log('handleWheel:', event)
  
  // deltaY < 0 表示向上滚动
  const isScrollingUp = event.deltaY < 0
  console.log('向上滑动:', isScrollingUp)
  
  
  console.log('滚轮滚动:', {
    deltaY: event.deltaY,
    isScrollingUp,
    scrollTop: messageContainer.value?.scrollTop
  })

  if(!imStore.hasMoreMessages) return
  // return
  // 向上滚动且在顶部时加载更多
  if (isScrollingUp && 
      messageContainer.value?.scrollTop <= 50 && 
      !isLoadingMore.value && 
      imStore.hasMoreMessages) {
    console.log('滚轮向上触发加载更多')
    loadMoreMessages()
  }
}

async function loadMoreMessages() {
  if (!imStore.currentConversation || isLoadingMore.value) return
  
  isLoadingMore.value = true
  
  // 记录当前可见的第一条消息作为锚点
  const firstVisibleMessage = imStore.messageList[0]
  if (firstVisibleMessage) {
    console.log('分界线:', firstVisibleMessage.ID)
    anchorMessageId.value = firstVisibleMessage.ID
    shouldScrollToAnchor.value = true
  }
  
  try {
    console.log('加载更多消息')
    await imStore.getMessageList(
      imStore.currentConversation.conversationID,
      firstVisibleMessage.ID
    )
    
    // 加载完成后，滚动到锚点消息
    // if (shouldScrollToAnchor.value && anchorMessageId.value) {
    //   nextTick(() => {
    //     scrollToMessage(anchorMessageId.value, 'center')
    //     shouldScrollToAnchor.value = false
    //   })
    // }
    
  } finally {
    isLoadingMore.value = false
  }
}

/**
 * 打开上传文件的弹窗
 */
const openFileUpload = () => {
  fileUploadDialogRef.value.open()
}
// 打开图片上传弹窗
const openImageUpload = () => {
  imageUploadDialogRef.value.open()
}

// 处理表情包选择
const handleEmojiSelect = (icon: string ) => {
  // 将表情插入到输入框的当前光标位置
  const textarea = messageInputRef.value?.$refs?.textarea || messageInputRef.value?.textarea
  if (textarea) {
    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    const text = inputMessage.value
    
    inputMessage.value = text.substring(0, start) + icon + text.substring(end)
    
    // 设置光标位置到表情后面
    nextTick(() => {
      const newPosition = start + icon.length
      textarea.setSelectionRange(newPosition, newPosition)
      textarea.focus()
    })
  } else {
    // 如果无法获取光标位置，直接追加到末尾
    inputMessage.value += icon
  }
}


// 格式化文件大小
const formatFileSize = (bytes: number | string): string => {
  if (!bytes) return ''
  const size = typeof bytes === 'string' ? parseInt(bytes) : bytes
  if (isNaN(size) || size === 0) return ''
  
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  const k = 1024
  const i = Math.floor(Math.log(size) / Math.log(k))
  
  if (i === 0) return size + ' B'
  return (size / Math.pow(k, i)).toFixed(1) + ' ' + units[i]
}

const getFileIcon = (fileName: string) => {
  if (!fileName) return '📄'
  const ext = fileName.split('.').pop()?.toLowerCase()
  const icons = {
    // 文档
    'pdf': '📕', 'doc': '📘', 'docx': '📘', 'txt': '📝',
    // 表格
    'xls': '📊', 'xlsx': '📊', 'csv': '📊',
    // 演示文稿
    'ppt': '📋', 'pptx': '📋',
    // 图片
    'jpg': '🖼️', 'jpeg': '🖼️', 'png': '🖼️', 'gif': '🖼️',
    // 压缩文件
    'zip': '🗜️', 'rar': '🗜️', '7z': '🗜️',
    // 音视频
    'mp3': '🎵', 'wav': '🎵', 'mp4': '🎬', 'avi': '🎬',
    // 代码
    'js': '💻', 'ts': '💻', 'vue': '💻', 'py': '🐍'
  }
  return icons[ext || ''] || '📄'
}

const downloadFile = (url: string, fileName: string) => {
  const link = document.createElement('a')
  link.href = url
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

/**
 * 预览图片
 * @param imgUrl 
 */
const handlerPreview = (imgUrl:string) => {
  previewImage.value = imgUrl
  dialogImageVisible.value = true
}

// 方法
async function selectConversation(conversation: Conversation) {

  await imStore.setCurrentConversation(conversation)
  // // 切换会话后滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
  console.log(imStore.messageList)
}

async function sendMessage() {
  const text = inputMessage.value.trim()
  if (!text) return
  
  inputMessage.value = ''
  console.log(imStore.currentConversation)

  const to = imStore.currentConversation?.userProfile?.userID
  if (!to) return
  try {
    const result = await imStore.sendTextMessage(
      text,
      to,
      'C2C',
    )
    console.log('发送消息结果:', result)
    if (result && result.code === 0) {
      console.log('消息发送成功')
      // 发送成功后滚动到底部
      // nextTick(() => {
      //   scrollToBottom()
      // })
      setTimeout(() => {
        if (messageContainer.value) {
          messageContainer.value.scrollTop = messageContainer.value.scrollHeight
        }
      }, 150)
    } else {
      ElMessage.error('发送失败')
    }
  } catch (error) {
    ElMessage.error('发送失败')
    console.error(error)
  }
}

async function sendProcurementNotice() {
  const procurementData = {
    type: 'procurement_notice',
    title: '采购通知',
    content: '您有新的采购订单需要处理',
    amount: 50000,
    deadline: '2024-01-15',
    status: 'pending',
  }

  try {
    const result = await imStore.sendCustomMessage(
      procurementData,
      '采购通知：您有新的采购订单需要处理',
      '109',
      'C2C',
    )

    if (result && result.code === 0) {
      console.log('IM自动重连成功')
      // 重连成功后获取会话列表
      await imStore.getConversationList()
    } else {
      console.log('IM自动重连失败')
    }
  } catch (error) {
    ElMessage.error('发送失败')
    console.error(error)
  }
}

function handleRefresh() {
  if (imStore.isLoggedIn) {
    imStore.getConversationList()
    ElMessage.success('刷新成功')
  }
}

function getConversationName(conversation: Conversation): string {
  if (conversation.type === 'C2C') {
    return conversation.userProfile?.nick || conversation.userProfile?.userID || '未知用户'
  } else {
    return conversation.groupProfile?.name || '未知群组'
  }
}

function getConversationAvatar(conversation: Conversation): string {
  if (conversation.type === 'C2C') {
    return conversation.userProfile?.avatar || ''
  } else {
    return conversation.groupProfile?.avatar || ''
  }
}

function getLastMessageText(message: Message | null): string {
  if (!message) return '暂无消息'
  
  if (message.type === 'TIMTextElem') {
    return message.payload?.text || '文本消息'
  } else if (message.type === 'TIMCustomElem') {
    const customData = parseCustomMessage(message)

    if (customData?.type === 'image') {
      return '[图片]'
    }
    else if (customData?.type === 'file') {
      return `[文件] ${customData.fileName}`
    }
    else if (customData?.type === 'announcement') {
      // return `[${customData.category}] ${customData.title}`
      return `[公告}`
    }
    else if (customData?.type === 'procurement_notice') {
      return '[采购通知]'
    }
    return message.payload?.description || '[自定义消息]'

  } else {
    return '[其他消息]'
  }
}

function parseCustomMessage(message: Message) {
  if (message.type !== 'TIMCustomElem') return null
  
  try {
    const data = JSON.parse(message.payload?.data || '{}')
    return {
      ...data,
      description: message.payload?.description,
      extension: message.payload?.extension,
    }
  } catch (error) {
    console.error('解析自定义消息失败:', error)
    return null
  }
}
function formatTime(timestamp: number): string {
  if (!timestamp) { return '' }

  const messageTime = dayjs(timestamp * 1000)
  const now = dayjs()
  const diffMinutes = now.diff(messageTime, 'minute')

  if (diffMinutes < 1) { return '刚刚' }
  if (diffMinutes < 60) { return `${diffMinutes}分钟前` }
  if (now.isSame(messageTime, 'day')) { return messageTime.format('HH:mm') }
  if (now.subtract(1, 'day').isSame(messageTime, 'day')) { return '昨天' }
  if (now.isSame(messageTime, 'year')) { return messageTime.format('MM-DD') }
  return messageTime.format('YYYY-MM-DD')
}


function formatMessageTime(timestamp: number): string {
  if (!timestamp) { return '' }

  const messageTime = dayjs(timestamp * 1000)
  const now = dayjs()

  if (now.diff(messageTime, 'minute') < 5) { return '刚刚' }
  if (now.isSame(messageTime, 'day')) { return messageTime.format('HH:mm') }
  if (now.subtract(1, 'day').isSame(messageTime, 'day')) { return `昨天 ${messageTime.format('HH:mm')}` }
  return messageTime.format('MM-DD HH:mm')
}

function showUserInfo(user: any) {
  console.log('显示用户信息:', user)
}

function scrollToBottom(force = false) {
  nextTick(() => {
    if (!messageContainer.value) return

    if (force) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
      return
    }

    const container = messageContainer.value
    const images = container.querySelectorAll('img')

    const performScroll = () => {
      container.scrollTop = container.scrollHeight
    }

    // 如果没有图片，直接滚动
    if (images.length === 0) {
      performScroll()
      return
    }

    // 等待所有图片加载完成
    let loadedCount = 0
    const timeoutId = setTimeout(performScroll, 1500) // 3秒超时保护

    const onImageLoad = () => {
      loadedCount++
      if (loadedCount === images.length) {
        clearTimeout(timeoutId)
        performScroll()
      }
    }

    // 检查每张图片的加载状态
    images.forEach((img: HTMLImageElement) => {
      if (img.complete && img.naturalWidth > 0) {
        // 图片已加载完成
        onImageLoad()
      } else {
        // 图片未加载完成，添加监听器
        const handleLoad = () => {
          img.removeEventListener('load', handleLoad)
          img.removeEventListener('error', handleLoad)
          onImageLoad()
        }
        
        img.addEventListener('load', handleLoad)
        img.addEventListener('error', handleLoad) // 加载失败也要计数
      }
    })
  })
}

// 生命周期
onMounted(async () => {
  // console.log('聊天页面加载，当前IM状态:', {
  //   isLoggedIn: imStore.isLoggedIn,
  //   tim: !!imStore.tim,
  //   conversationList: imStore.conversationList.length,
  //   currentConversation: !!imStore.currentConversation
  // })
  
  // 如果IM未登录，尝试自动重连
  if (!imStore.isLoggedIn || !imStore.tim) {
    console.log('IM未登录，尝试自动重连...')
    try {
      const result = await imStore.autoReconnect()
      if (result && result.code === 0) {
        console.log('IM自动重连成功')
        // 重连成功后获取会话列表
        await imStore.getConversationList()
      } else {
        console.log('IM自动重连失败')
      }
    } catch (error) {
      console.log('IM自动重连异常:', error)
    }
  } else {
    // 如果已登录，获取会话列表
    try {
      await imStore.getConversationList()
    } catch (error) {
      console.log('获取会话列表失败:', error)
    }
  }
  
  // // 只有在有当前会话时才滚动到底部
  // if (imStore.currentConversation) {
  //   nextTick(() => {
  //     scrollToBottom()
  //   })
  // }
})

// 监听消息列表变化
watch(() => imStore.messageList, (newList, oldList) => {
  // 如果正在加载更多消息，不要自动滚动到底部
  if (isLoadingMore.value) {
    console.log('正在加载更多消息，跳过自动滚动')
    return
  }
  if (imStore.currentConversation && newList && newList.length > 0 && !isLoadingMore.value) {
    // 首次进入或收到新消息时，记录最后一条消息并滚动到底部
    const lastMessage = newList[newList.length - 1]
    anchorMessageId.value = newList[0].ID
    
    nextTick(() => {
      scrollToBottom()
    })
  }
}, { deep: true })

// 监听当前会话变化，滚动到底部
watch(() => imStore.currentConversation, (newConversation: Conversation, oldConversation: Conversation) => {
  if (newConversation) {
    // 延迟更长时间，确保消息列表和图片都加载完成
    setTimeout(() => {
      scrollToBottom()
    }, 800) // 从300ms增加到800ms
  }
})
</script>


<style scoped lang="scss">
.announcement-message {
  background: #f3f4f6;
  /* color: white; */
  padding: 12px;
  border-radius: 8px;
  
  .announcement-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    
    .announcement-icon {
      margin-right: 8px;
      font-size: 18px;
    }
    
    .announcement-title {
      font-weight: 600;
      font-size: 14px;
    }
  }
  
  .announcement-content {
    font-size: 13px;
    line-height: 1.4;
    margin-bottom: 8px;
  }
  
  .announcement-date {
    font-size: 11px;
    opacity: 0.8;
  }
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  color: #909399;
  font-size: 12px;
  gap: 5px;
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  color: #909399;
  font-size: 14px;
  gap: 8px;
}

.no-more-messages {
  display: flex;
  justify-content: center;
  padding: 12px;
  color: #c0c4cc;
  font-size: 12px;
}
.custom-file-message {
  .file-container {
    display: flex;
    gap: 8px;
    padding: 8px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    background: #f8f9fa;
  }
  
  .file-icon {
    font-size: 20px;
  }
  
  .file-info {
    flex: 1;
    .file-name {
      font-weight: 500;
      color: #303133;
    }
    .file-size {
      font-size: 12px;
      color: #909399;
      margin-top: 4px;
    }
  }
  
  .download-btn {
    padding: 4px 8px;
    font-size: 12px;
    background: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }
}
::v-deep  .el-dialog__body {
  padding: 20px;
}
/* 自定义图片消息样式 */
.custom-image-message {
  max-width: 200px;
}

.custom-message-image {
  width: 100%;
  max-width: 200px;
  height: auto;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.custom-message-image:hover {
  transform: scale(1.02);
}

.chat-container {
  display: flex;
  height: 100vh;
  width: 100%;
  background: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
}

/* 左侧边栏 */
.sidebar {
  width: 260px;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #e4e7ed;
}

.sidebar-header {
  padding: 16px 16px 12px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.sidebar-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.refresh-btn {
  width: 28px;
  height: 28px;
  background: #303133;
  border: none;
  border-radius: 4px;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

/* 搜索框 */
.search-box {
  padding: 12px 16px;
  background: #ffffff;
  border-bottom: 1px solid #f5f7fa;
}

.search-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
  background: #f8f9fa;
}

.search-input:focus {
  border-color: #409eff;
  background: #ffffff;
}

/* 会话列表 */
.conversation-list {
  flex: 1;
  overflow-y: auto;
  background: #ffffff;
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f5f7fa;
  transition: background-color 0.2s ease;
}

.conversation-item:hover {
  background: #f8f9fa;
}

.conversation-item.active {
  background: #ecf5ff;
}

.avatar-container {
  position: relative;
  margin-right: 12px;
  flex-shrink: 0;
}

.unread-count {
  position: absolute;
  top: -2px;
  right: -2px;
  background: #f56c6c;
  color: white;
  font-size: 10px;
  font-weight: 600;
  padding: 2px 6px;
  border-radius: 8px;
  min-width: 16px;
  text-align: center;
}

.conversation-info {
  flex: 1;
  min-width: 0;
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.name {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.time {
  font-size: 12px;
  color: #909399;
  flex-shrink: 0;
  margin-left: 8px;
}

.last-message {
  color: #909399;
  font-size: 13px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin: 0;
}

/* 右侧聊天区域 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #ffffff;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex: 1;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  padding: 40px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
}

.empty-content {
  text-align: center;
  max-width: 320px;
}

.empty-icon {
  width: 64px;
  height: 64px;
  margin: 0 auto 20px;
  position: relative;
  opacity: 0.6;
}

.icon-message {
  display: block;
  width: 100%;
  height: 100%;
  position: relative;
}

.icon-message::before {
  content: '';
  position: absolute;
  width: 48px;
  height: 36px;
  border: 3px solid #c0c4cc;
  border-radius: 8px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.icon-message::after {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-top: 8px solid #c0c4cc;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
}

.empty-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 12px 0;
  line-height: 1.4;
}

.empty-description {
  font-size: 14px;
  color: #909399;
  margin: 0 0 32px 0;
  line-height: 1.6;
}

.empty-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
}

.action-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 10px 20px;
  font-size: 14px;
  font-weight: 500;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  outline: none;
}

.action-btn.primary {
  background: #409eff;
  color: white;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

.action-btn.primary:hover {
  background: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.4);
}

.action-btn.primary:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

.icon-refresh {
  display: inline-block;
  width: 14px;
  height: 14px;
  position: relative;
}

.icon-refresh::before {
  content: '';
  position: absolute;
  width: 12px;
  height: 12px;
  border: 2px solid currentColor;
  border-radius: 50%;
  border-top-color: transparent;
  top: 1px;
  left: 1px;
}

.icon-refresh::after {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  border-left: 3px solid transparent;
  border-right: 3px solid transparent;
  border-bottom: 4px solid currentColor;
  top: -1px;
  right: 2px;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.chat-user {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-info h3 {
  margin: 0 0 2px 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.user-status {
  font-size: 12px;
  color: #909399;
}

/* 消息区域 */
.message-area {
  flex: 1;
  overflow-y: auto;
  padding: 16px 20px;
  background: #f8f9fa;
  scroll-behavior: smooth;
}

.message-wrapper {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
}

.message-wrapper.message-right {
  flex-direction: row-reverse;
}

.message-wrapper.message-right .message-content {
  align-items: flex-end;
}

.message-wrapper.message-right .message-info {
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 8px;
  flex-shrink: 0;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 60%;
}

.message-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
  font-size: 12px;
  color: #909399;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 8px;
  background: #ffffff;
  border: 1px solid #e4e7ed;
  word-wrap: break-word;
  line-height: 1.5;
  font-size: 14px;
  color: #303133;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.bubble-self {
  background: #409eff;
  color: white;
  border: none;
}

/* 采购通知样式 */
.procurement-notice {
  background: #409eff !important;
  color: white !important;
  border: none !important;
  padding: 16px;
  border-radius: 8px;
}

.notice-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-weight: 600;
}

.notice-content {
  margin-bottom: 12px;
  line-height: 1.4;
}

.notice-details {
  font-size: 12px;
  opacity: 0.9;
}

.notice-details div {
  margin-bottom: 4px;
}

.notice-status {
  display: inline-block;
  padding: 2px 8px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  font-size: 11px;
  margin-left: 8px;
}

/* 输入区域 */
.input-section {
  padding: 12px 20px 16px;
  border-top: 1px solid #e4e7ed;
  background: #ffffff;
}

.input-toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.tool-btn {
  width: 28px;
  height: 28px;
  border: none;
  background: transparent;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.tool-btn:hover {
  background: #f5f7fa;
}

.input-row {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  margin-bottom: 8px;
}

.message-input {
  flex: 1;
}

.send-btn {
  padding: 8px 16px;
  font-size: 14px;
}

.input-hint {
  font-size: 12px;
  color: #c0c4cc;
  text-align: right;
}

/* 滚动条样式 */
.conversation-list::-webkit-scrollbar,
.message-area::-webkit-scrollbar {
  width: 4px;
}

.conversation-list::-webkit-scrollbar-track,
.message-area::-webkit-scrollbar-track {
  background: transparent;
}

.conversation-list::-webkit-scrollbar-thumb,
.message-area::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 2px;
}
</style>